//
//  EmoticonView.swift
//  Emoticon
//
//  Created by 李锡鹏 on 2017/6/10.
//  Copyright © 2017年 李锡鹏. All rights reserved.
//

import UIKit
import SnapKit
private let EmoticonViewCellId = "EmoticonViewCellId"
class EmoticonView: UIView {
    init(selectedEmoticon:@escaping (_ emoticon:Emoticon) ->()) {
        selectedEmoticonCallBack = selectedEmoticon
        var rect = UIScreen.main.bounds
        rect.size.height = 216
        super.init(frame: rect)
        backgroundColor = UIColor.red
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var selectedEmoticonCallBack:(_ emoticon:Emoticon) ->()
    // 表情集合视图
    private lazy var colletionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: EmoticonLayout())
    // 表情工具栏
    private lazy var toolBarView = UIToolbar()
    
    lazy var packages = EmoticonManager.sharedManager.packages
    
    func setupUI() {
        backgroundColor = UIColor.white
        //1 添加控件
        addSubview(colletionView)
        addSubview(toolBarView)
        //2 布局
        colletionView.snp.makeConstraints { (make) in
            make.top.equalTo(self.snp.top)
            make.left.equalTo(self.snp.left)
            make.right.equalTo(self.snp.right)
            make.bottom.equalTo(toolBarView.snp.top)
        }
        toolBarView.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.snp.bottom)
            make.left.equalTo(self.snp.left)
            make.right.equalTo(self.snp.right)
            make.height.equalTo(36)
        }
        prepareColletionView()
        prepareToolbar()
    }
    
    
    func prepareToolbar() {
        tintColor = UIColor.darkGray
        var items = [UIBarButtonItem]()
        var index = 0
        for package in packages {
            // 添加按钮
            items.append(UIBarButtonItem(title: package.group_naem_cn, style: UIBarButtonItemStyle.plain, target: self, action: #selector(toolbarClick(item:))))
            items.last?.tag = index
            index += 1
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBarView.items = items
    }
    
    
    
    func prepareColletionView() {
        colletionView.backgroundColor = UIColor.lightGray
        //注册cell
        colletionView.register(EmoticonCellView.self, forCellWithReuseIdentifier: EmoticonViewCellId)
        //指定数据源
        colletionView.dataSource = self
        colletionView.delegate = self as? UICollectionViewDelegate
    }
    
    func toolbarClick(item: UIBarButtonItem) {
        print("点击了tag为:\(item.tag)的按钮")
        let indexPath = NSIndexPath(item: 0, section: item.tag)
        colletionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: true)
    }
    
}
extension EmoticonView: UICollectionViewDataSource
{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonViewCellId, for: indexPath) as! EmoticonCellView
        cell.emoticon=packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
}
extension EmoticonView:UICollectionViewDelegate
{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let em = packages[indexPath.section].emoticons[indexPath.item]
        selectedEmoticonCallBack(em)
    }
}
class EmoticonLayout:UICollectionViewFlowLayout
{
    override func prepare() {
        super.prepare()
        let row:CGFloat = 3
        let col:CGFloat = 7
        let w = (collectionView?.bounds.width)! / col
        let margin = CGFloat(((collectionView?.bounds.height)! - w*row) / 2)
        minimumLineSpacing=0
        minimumInteritemSpacing=0
        itemSize = CGSize(width: w, height: w)
        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        scrollDirection = .horizontal
        collectionView?.isPagingEnabled = true
        collectionView?.bounces = false
    }
}
class EmoticonCellView: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    var emoticonButton:UIButton = UIButton()
    var emoticon: Emoticon? {
        didSet {
            emoticonButton.setTitle(emoticon?.emoji, for: .normal)
            emoticonButton.setImage(UIImage(named:emoticon?.imagePath ?? ""), for: .normal)
            if (emoticon?.isRemoved)!
            {
                emoticonButton.setImage(UIImage(named:"compose_emotion_delete"), for: .normal)
            }
            
            
            
            
        }
    }
    func setupUI() {
        
        contentView.addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.white
        emoticonButton.titleLabel?.font = UIFont.systemFont(ofSize: 32)
        emoticonButton.setTitleColor(UIColor.black, for: .normal)
        emoticonButton.frame = contentView.bounds.insetBy(dx: 4, dy: 4)//边距
        emoticonButton.isUserInteractionEnabled = false
    }
}


